home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Musique / Quod Libet / quodlibet-3.3.0-installer.exe / bin / quodlibet / util / json_data.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2014-12-31  |  5KB  |  148 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. from __future__ import absolute_import
  5. import json
  6. from collections import namedtuple
  7. from quodlibet.util.dprint import print_d, print_w
  8.  
  9. class JSONObject(object):
  10.     '''
  11.     Base class for simple, named data objects
  12.     that can be edited and persisted as JSON.
  13.     '''
  14.     NAME = ''
  15.     Field = namedtuple('Field', [
  16.         'human_name',
  17.         'doc'])
  18.     EMPTY_FIELD = Field(None, None)
  19.     FIELDS = { }
  20.     
  21.     def _should_store(cls, field_name):
  22.         '''Decides if a field should be stored'''
  23.         return not field_name.startswith('_')
  24.  
  25.     _should_store = classmethod(_should_store)
  26.     
  27.     def __init__(self, name):
  28.         if not name:
  29.             raise ValueError('%s objects must be named' % type(self).__name__)
  30.         self.name = str(name)
  31.  
  32.     
  33.     def data(self):
  34.         '''A list of tuples of the persisted key:values in this class'''
  35.         if self.FIELDS:
  36.             for k in self.FIELDS:
  37.                 pass
  38.             continue
  39.             return k[(self.__getattribute__(k), None)]
  40.         print_d('No order specified for class %s' % type(self).__name__)
  41.         return dict([ (k, v) for k, v in self.__dict__.items() if self._should_store(k) ])
  42.  
  43.     data = property(data)
  44.     
  45.     def field(self, name):
  46.         '''Returns the Field metadata of field `name` if available,
  47.         or an null / empty one'''
  48.         if isinstance(self.FIELDS, dict):
  49.             return self.FIELDS.get(name, self.EMPTY_FIELD)
  50.  
  51.     
  52.     def json(self):
  53.         return json.dumps(dict(self.data))
  54.  
  55.     json = property(json)
  56.     
  57.     def __cmp__(self, other):
  58.         return cmp(self.data, other.data)
  59.  
  60.     
  61.     def __str__(self):
  62.         return "<%s '%s' with %s>" % (self.__class__.__name__, self.name, self.json)
  63.  
  64.  
  65.  
  66. class JSONObjectDict(dict):
  67.     '''A dict wrapper to persist named `JSONObject`-style objects'''
  68.     
  69.     def __init__(self, Item = JSONObject):
  70.         self.Item = Item
  71.         dict.__init__(self)
  72.  
  73.     
  74.     def from_json(cls, ItemKind, json_str):
  75.         '''
  76.         Factory method for building from an input string,
  77.         a JSON map of {item_name1: {key:value, key2:value2...}, item_name2:...}
  78.         '''
  79.         new = cls(ItemKind)
  80.         
  81.         try:
  82.             data = json.loads(json_str)
  83.         except ValueError:
  84.             print_w('Broken JSON: %s' % json_str)
  85.  
  86.         for name, blob in data.items():
  87.             
  88.             try:
  89.                 new[name] = ItemKind(**blob)
  90.             continue
  91.             except TypeError:
  92.                 e = None
  93.                 raise IOError("Couldn't instantiate %s from JSON (%s)" % (ItemKind.__name__, e))
  94.                 continue
  95.             
  96.  
  97.         
  98.         return new
  99.  
  100.     from_json = classmethod(from_json)
  101.     
  102.     def from_list(cls, json_objects, raise_errors = True):
  103.         new = cls()
  104.         for j in json_objects:
  105.             if not isinstance(j, JSONObject):
  106.                 msg = 'Incorrect type (%s) found in list of objects' % j.__class__.__name__
  107.                 if raise_errors:
  108.                     raise TypeError(msg)
  109.                 print_d(msg)
  110.                 continue
  111.             if not (j.name) and raise_errors:
  112.                 raise ValueError('Null key for %s object %s' % (cls.__name__, j))
  113.             if j.name in new:
  114.                 print_w("Duplicate %s found named '%s'. Removing..." % (cls.__name__, j.name))
  115.             new[j.name] = j
  116.         
  117.         return new
  118.  
  119.     from_list = classmethod(from_list)
  120.     
  121.     def save(self, filename = None):
  122.         '''
  123.         Takes a list of `JSONObject` objects and returns
  124.         the data serialised as a JSON string,
  125.         also writing (prettily) to file `filename` if specified.
  126.         '''
  127.         print_d('Saving %d %s(s) to JSON..' % (len(self), self.Item.__name__))
  128.         
  129.         try:
  130.             obj_dict = dict([ (o.name, dict(o.data)) for o in self.values() ])
  131.         except AttributeError:
  132.             raise 
  133.  
  134.         json_str = json.dumps(obj_dict, indent = 4)
  135.         if filename:
  136.             
  137.             try:
  138.                 with open(filename, 'wb') as f:
  139.                     f.write(json_str)
  140.             except IOError:
  141.                 e = None
  142.                 print_w("Couldn't write JSON for %s object(s) (%s)" % (type(self).__name__, e))
  143.             
  144.  
  145.         return json_str
  146.  
  147.  
  148.